package com.xuanjia.smart_interview.job.cycle;

import cn.hutool.core.collection.CollUtil;
import com.xuanjia.smart_interview.constant.FileConstant;
import com.xuanjia.smart_interview.esdao.QuestionEsDao;
import com.xuanjia.smart_interview.mapper.QuestionMapper;
import com.xuanjia.smart_interview.model.dto.question.QuestionEsDTO;
import com.xuanjia.smart_interview.model.entity.Question;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class IncSyncQuesitonToEs {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private QuestionEsDao questionEsDao;

    @Scheduled(fixedRate = 60 * 1000)
    public void run(){
        Long FIVE_MINUTES = 5 * 60 * 1000L;
        Date deleteFiveMinutes = new Date(new Date().getTime() - FIVE_MINUTES);
        List<Question> questionList = questionMapper.listQuestionWithDelete(deleteFiveMinutes);
        if (CollUtil.isEmpty(questionList)) {return;}
        try {
            List<QuestionEsDTO> questionEsDTOS = questionList.stream()
                    .map(QuestionEsDTO::objToDto)
                    .collect(Collectors.toList());
            int total = questionList.size();
            final int pageSize = 500;
            log.info("IncSyncQuestionToEs start, total {}", total);
            for (int i = 0; i < total; i += pageSize) {
                int pageEnd = Math.min(i + 500, total);
                log.info("sync from {} to {}", i, pageEnd);
                questionEsDao.saveAll(questionEsDTOS.subList(i, pageEnd));
            }
            log.info("IncSyncQuestionToEs end, total {}", total);
        } catch (Exception e) {
        log.error("Error occurred in IncSyncQuesitonToEs: ", e);
    }
    }
}
